package com.mdinic.blogovi.front.page.person.picture;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.file.File;
import org.apache.wicket.util.file.Files;
import org.apache.wicket.util.file.Folder;
import org.apache.wicket.util.lang.Bytes;

import com.mdinic.blogovi.front.common.AbstractBasePage;
import com.mdinic.blogovi.front.page.BSession;
import com.mdinic.blogovi.front.page.person.PersonViewPage;
import com.mdinic.blogovi.service.PersonService;

public class UploadPhotoPage extends AbstractBasePage {

    private static final String PNG = "png";

    private static final long serialVersionUID = 1L;

    @SpringBean
    private PersonService personService;

    /**
     * Constructor.
     */
    public UploadPhotoPage() {
        super(true);

        final String fileName = "I" + UUID.randomUUID().toString().replace("-", "") + ".png";

        final FileUploadField fileUploadField = new FileUploadField("file");
        Form<Void> form = new Form<Void>("form") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit() {
                final FileUpload upload = fileUploadField.getFileUpload();
                if (upload != null) {
                    // Create a new file
                    File newFile = new File(getUploadFolder(), fileName);

                    File newSmallFile = new File(getUploadSmallFolder(), fileName);

                    // Check new file, delete if it already existed
                    // removeIfFileExists(newFile);
                    try {
                        // Save to new file
                        newFile.createNewFile();
                        newSmallFile.createNewFile();
                        upload.writeTo(newFile);

                        BufferedImage bufferedImage = ImageIO.read(newFile);
                        Image image = bufferedImage.getScaledInstance(-1, 128, java.awt.Image.SCALE_SMOOTH);
                        Image smallImage = bufferedImage.getScaledInstance(-1, 24, java.awt.Image.SCALE_SMOOTH);
                        ImageIO.write(toBufferedImage(image), PNG, newFile);
                        ImageIO.write(toBufferedImage(smallImage), PNG, newSmallFile);

                        PageParameters parameters = new PageParameters();
                        parameters.add(PersonViewPage.URL_PARAM_NAME, BSession.get().getPerson().getId());

                        // remove old picture if exists
                        if (BSession.get().getPerson().getPicture() != null) {
                            removeIfFileExists(new File(getUploadFolder(), BSession.get().getPerson().getPicture()));
                            removeIfFileExists(new File(getUploadSmallFolder(), BSession.get().getPerson().getPicture()));
                        }

                        BSession.get().setPerson(
                                personService.updateImage(BSession.get().getPerson().getId(), fileName));
                        setResponsePage(PersonViewPage.class, parameters);
                    } catch (Exception e) {
                        e.printStackTrace();
                        removeIfFileExists(newFile);
                        // TODO log
                    }
                }
            }
        };
        form.setMaxSize(Bytes.kilobytes(500));
        form.add(fileUploadField);
        form.setMultiPart(true);

        // Create feedback panels
        final FeedbackPanel uploadFeedback = new FeedbackPanel("feedback");

        // Add uploadFeedback to the page itself
        add(uploadFeedback);

        // Add simple upload form, which is hooked up to its feedback panel by
        add(form);

    }

    private void removeIfFileExists(File newFile) {
        if (newFile.exists()) {
            // Try to delete the file
            if (!Files.remove(newFile)) {
                throw new IllegalStateException("Unable to overwrite " + newFile.getAbsolutePath());
            }
        }
    }

    private Folder getUploadFolder() {
        return new Folder(personService.getUploadPhotoPathPerson());
    }

    private Folder getUploadSmallFolder() {
        return new Folder(personService.getUploadPhotoPathPersonSmall());
    }

    private static BufferedImage toBufferedImage(Image src) {
        int w = src.getWidth(null);
        int h = src.getHeight(null);
        int type = BufferedImage.TYPE_INT_RGB; // other options
        BufferedImage dest = new BufferedImage(w, h, type);
        Graphics2D g2 = dest.createGraphics();
        g2.drawImage(src, 0, 0, null);
        g2.dispose();
        return dest;
    }
}
